<template>
  <div class="login">
    <div class="backendImg" :style="{'background-image':bg}">
      <img class="login-logo" src="../../assets/images/supplierDisplayCenter/logo.png"/>
      <div class="loginCount">
        <p class="login-title">登录</p>
        <div class="login-item">
          <div class="login-label">
            <img src="../../assets/images/login/user.svg" alt/>
            登录名：
          </div>
          <a-input
            type="text"
            placeholder="请输入登录名"
            v-model="username"
            @keyup.enter="pressEnter"
            name="username"
            ref="username"
          />
        </div>

        <div class="login-item">
          <div class="login-label">
            <img src="../../assets/images/login/pwd.svg" alt/>
            密码：
          </div>
          <a-input
            type="password"
            placeholder="请输入密码"
            v-model="pwd"
            @keyup.enter="pressEnter"
            name="password"
            ref="password"
          />
        </div>

        <div class="login-item">
          <div class="login-label">
            <img src="../../assets/images/login/code.svg" alt/>
            验证码：
          </div>
          <div style="display: flex;">
            <a-input
              type="text"
              placeholder="请输入验证码"
              v-model="code"
              @keyup.enter="pressEnter"
              name="code"
              style="width: 150px;"
              ref="code"
            />
            <img class="code" :src="codeUrl" @click="getCode"/>
          </div>
        </div>
        <div class="loginBtnBox" @click="login">
          登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录
        </div>
      </div>
    </div>
    <a-modal
      :maskClosable="false"
      :footer="null"
      @cancel="selectDeptVisible=false"
      v-model="selectDeptVisible"
    >
      <company-type :userList="userList" :pwd="pwd" :loginData="loginData"
                    @failed="onDeptSelectLoginFailed"></company-type>
    </a-modal>
    <a-modal
      title="请选择登录方式"
      :maskClosable="false"
      :footer="null"
      @cancel="loginWayChoiceFlag=false"
      v-model="loginWayChoiceFlag"
    >
      <a-row>
        <a-col style="text-align: center;">
          <a-button type="primary" @click="choiceLogin('moblie')" style="width: 150px;">手机号登录</a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col style="text-align: center;margin-top: 40px;">
          <a-button type="primary" @click="choiceLogin('jobNo')" style="width: 150px;">工号登录</a-button>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import storage from '@/utils/storage'
import {appConfig} from '../../config/app'
import {
  getPwdStrategy,
  checkJobNoMobileForXb,
  checkUserNumByMobileBeforeLoginForXb,
  encryptPwd,
  getPublicKey,
  qryUserRefDetail
} from '../../api/login'
import { getSetting } from '@/api/system/permission'
import {checkPassWord} from '../../utils/func'
import CompanyType from '../../components/login/CompanyType'

export default {
  name: 'Login',
  components: {
    CompanyType
  },
  data () {
    return {
      username: '',
      pwd: '',
      code: '',
      loading: false,
      isDisabled: false,
      codeKey: '',
      codeUrl: '',
      selectDeptVisible: false,
      userList: [],
      loginData: {},
      loginWayChoice: '',//登录方式
      loginWayChoiceFlag: false,
      bg: 'url(' + require('../../assets/images/login/loginBg.png') + ')'
    }
  },
  created () {
    storage.session.remove('isLogin')
    storage.session.remove('authToken')
    storage.session.remove('userInfo')
    storage.session.remove('topPermTree')
    storage.session.remove('role')
    storage.session.remove('roles')
	storage.session.remove('wallet')
    this.getConfig()
    this.getCode()
    this.getSetting()
  },
  mounted () {
    this.$refs.username.focus()
    this.$refs.password.onkeyup = e => {
      e = window.event || e
      if (e.code == 'Enter' || e.code == 'enter') {
        this.login()
      }
    }
    this.$refs.code.onkeyup = e => {
      e = window.event || e
      if (e.code == 'Enter' || e.code == 'enter') {
        this.login()
      }
    }
    window.addEventListener("keydown", this.keyDown)

  },
  methods: {
     // 点击回车键登录
     keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.login(); // 定义的登录方法
      }
    },
    pressEnter (e) {
      let name = e.target.name
      switch (name) {
        case 'username':
          this.$refs.password.focus()
          break
        case 'password':
          this.$refs.code.focus()
          break
      }
    },
    getConfig () {
      getPwdStrategy().then(response => {
        if (response.code === 0) {
          appConfig.passwdStrategy = response.data
          storage.session.set('passwdStrategy', response.data)
        }
      })
    },
    getCode () {
      this.codeKey = Math.floor((Math.random() * 1000000000) + 1)
      this.codeUrl = appConfig.microServ + appConfig.microServModules.system + 'api/login/verifyCode?key=' + this.codeKey
    },
    getSetting(){
      getSetting().then(response => {
        if (response.code === 0) {
          console.log('getsetting',response.data)
          // appConfig.passwdStrategy = response.data
          // storage.session.set('passwdStrategy', response.data)
        }
      })
    },
    async login () {
      if (this.username === '') {
        this.$message.error('用户名不能为空！')
        this.$refs.username.focus()
        return false
      }
      if (this.pwd === '') {
        this.$message.error('密码不能为空！')
        this.$refs.password.focus()
        return false
      }
      if (!this.code) {
        this.$message.error('验证码不能为空！')
        this.$refs.code.focus()
        return false
      }

      this.loading = true
      this.isDisabled = true

      let publicKey = await getPublicKey(this.username)
      let encryptedPwd = this.pwd
      if (publicKey.data.publicKey) {
        encryptedPwd = encryptPwd(publicKey, this.pwd)
      }
      let data = {
        userCode: this.username,
        passwd: encryptedPwd,
        key: publicKey.data.key,
        verifyCode: this.code,
        verifyKey: this.codeKey,
        isShowPwdErrInfo: '0',
        uuid: '',
        mobileCode: ''
      }

      this.checkJobNoMobile(data)
    },
    checkJobNoMobile (data) {
      checkJobNoMobileForXb(data).then(response => {
        console.log(response)
        if (response.code === 0) {
          let loginWayChoice = response.data
          this.loginWayChoice = loginWayChoice
          this.loginWayChoiceFlag = loginWayChoice === 'choose'
          if (!this.loginWayChoiceFlag) {
            data.loginWaychoice = loginWayChoice
            this.checkUserNumByMobileBeforeLogin(data)
          }
        } else {
          this.getCode()
          this.loading = false
          this.isDisabled = false
        }
      })
    },
    async choiceLogin (type) {
      let publicKey = await getPublicKey(this.username)
      let encryptedPwd = this.pwd
      if (publicKey.publicKey) {
        encryptedPwd = encryptPwd(publicKey, this.pwd)
      }
      let data = {
        userCode: this.username,
        passwd: encryptedPwd,
        key: publicKey.key,
        verifyCode: this.code,
        verifyKey: this.codeKey,
        loginWayChoice: type,
        isShowPwdErrInfo: this.isShowPwdErrInfo,
      }
      this.loginWayChoiceFlag = false
      this.checkUserNumByMobileBeforeLogin(data)
    },
    checkUserNumByMobileBeforeLogin (data) {
      checkUserNumByMobileBeforeLoginForXb(data).then(response => {
        if (response.code === 0) {
          this.loginHandle(response.data)
          // 权限分配
        } else if (response.code === 1) {
          // 检验是否能正常登陆
          this.checkLogin(response, data)
        } else {
          this.getCode()
        }
        this.loading = false
        this.isDisabled = false
      }).catch(err => {
        console.log(err)
        this.getCode()
        this.code = ''
        this.loading = false
        this.isDisabled = false
      })
    },
    // 校验密码强度
    checkPwdStrategy () {
      let isChangePasswd = false
      if (appConfig.passwdStrategy && appConfig.passwdStrategy.enable && checkPassWord(appConfig.passwdStrategy.length, this.pwd) < appConfig.passwdStrategy.level) {
        isChangePasswd = true
      }
      return isChangePasswd
    },
    checkLogin (response, loginData) {
      let isChangePasswd = this.checkPwdStrategy()
      let data = response.data
      let changePwd = data.changePwd
      if (isChangePasswd) {
        this.tipInfo('您的登录密码安全系数太低，需要重置密码！', loginData)
      } else if (changePwd) {
        this.tipInfo(response.message, loginData)
      } else {
        this.selectDeptVisible = true
        let userList = []
        for (let i in data) {
          let fullDeptName = data[i].fullDeptName
          data[i].fullDeptName = fullDeptName.substring(0, fullDeptName.length - 1)
          data[i].pwd = this.pwd
          let user = {
            userCode: data[i].userCode,
            fullDeptName: data[i].fullDeptName,
            undoCount: data[i].undoCount,
          }
          userList.push(user)
        }
        // 把登陆参数传入部门弹出框
        this.userList = userList
        this.loginData = loginData
        // 把多部门信息存入
        storage.session.set('userList', this.userList)
      }
    },
    tipInfo (msg, data) {
      let that = this
      this.$warning({
        content: msg,
        onOk () {
          storage.session.set('mobile', data.userCode)
          that.$router.push({path: '/resetPassword'})
        },
        okText: '确认'
      })
    },
    loginHandle (data) {
      let isChangePasswd = this.checkPwdStrategy()
      const that = this
      if (isChangePasswd) {
        if (!data.mobile) {
          this.$error({
            content: '未找到您的手机号码信息，请联系单位管理员完善个人信息后再登录！',
          })
        } else {
          this.$warning({
            content: '您的登录密码安全系数太低，需要重置密码！',
            onOk () {
              storage.session.set('mobile', data.mobile)
              that.$router.push({path: '/resetPassword'})
            },
            okText: '确认'
          })
        }
      } else {
        this.loginAfter(data)
      }
    },
    async loginAfter (data) {
      console.log(data)
      storage.session.set('authToken', data.authToken)
      qryUserRefDetail().then(res => {
        if(res.code == 0) {
        res.data.userInfo.deptInfo = res.data.deptInfo

          storage.session.set('userInfo', res.data.userInfo)

        }
      })
      const tempRoleMap = {
        '1': 'DATA_REQUESTER',
        '2': 'DATA_PRODUCER',
        '3': 'DATA_BUSINESS',
        '4': 'DT_THIRD_SERVERS',
        '5': 'DATA_OPERATION_ADMIN',
        '7': 'DATA_COMPLIANCE_ADMIN',
        '6': 'DATA_MARKET_ADMIN',
      }
      storage.session.set('role', tempRoleMap[data.userType] || 'DATA_REQUESTER')
      this.$store.commit('setRole', tempRoleMap[data.userType] || 'DATA_REQUESTER')

      storage.session.set('roles', [tempRoleMap[data.userType]] || ['DATA_REQUESTER'])
      storage.session.set('isLogin', true)
      this.$router.push('/portal')
    },
    // 多部门选择登录时超时或其他原因登陆失败
    onDeptSelectLoginFailed () {
      this.selectDeptVisible = false
      this.loading = false
      this.isDisabled = false
    },
    goTo (url) {
      this.$router.push(url)
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;

  .backendImg {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
  }

  .login-logo {
    width: 190px;
    height: auto;
    position: absolute;
    top: 50px;
    left: 60px;
  }

  .loginCount {
    padding: 40px 50px;
    background: #FFFFFF;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    border-radius: 10px;

    .login-title {
      width: 300px;
      color: rgba(50, 50, 50, 1);
      font-family: PingFangSC-Medium, sans-serif;
      font-size: 20px;
      color: #323232;
      text-align: center;
      font-weight: 500;
    }

    .login-item {
      width: 300px;
      margin-top: 20px;

      .login-label {
        display: flex;
        align-items: center;
        font-family: PingFangSC-Regular, sans-serif;
        font-size: 14px;
        color: #909090;
        font-weight: 400;
        margin-bottom: 10px;

        img {
          height: 20px;
          margin-right: 10px;
        }
      }

      input {
        width: 100%;
        height: 40px;
        outline: none;
        border: 1px solid rgba(199, 199, 199, 1);
        border-radius: 4px;
      }

      .code {
        flex: 1;
        margin-left: 10px;
        height: 40px;
        border: 1px solid rgba(199, 199, 199, 1);
        border-radius: 2px;
      }
    }

    .VerCodeBox {
      display: flex;

      .VerCode {
        width: 62%;
        height: 40px;
        background: rgba(245, 245, 245, 1);
        border-radius: 20px;
        margin-bottom: 24px;

        img {
          width: 22px;
          margin-left: 20px;
        }

        input {
          border: none;
          width: 64%;
          height: 40px;
          outline: none;
          background: rgba(245, 245, 245, 1);
          margin-left: 6px;
        }
      }

      .v_container {
        margin-left: 20px;
      }
    }

    .loginBtnBox {
      width: 100%;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background: #006CD4;
      border-radius: 4px;
      margin-top: 30px;
      cursor: pointer;
      font-family: PingFangSC-Regular, sans-serif;
      font-size: 16px;
      color: #FFFFFF;
      font-weight: 400;
    }
  }
}

.forgetPwd {
  font-family: PingFangSC-Regular, sans-serif;
  font-size: 14px;
  color: #909090;
  font-weight: 400;
  cursor: pointer;

  &:hover {
    color: #006CD4;
  }
}
</style>
